package com.xl.config;

import com.xl.Resources;
import com.xl.pojo.Configuration;
import com.xl.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(String mapperPath) {
        try {
            InputStream inputStream = Resources.getResourcesAsStream(mapperPath);
            Document document = new SAXReader().read(inputStream);
            //Mapper
            Element rootElement = document.getRootElement();
            String namespace = rootElement.attributeValue("namespace");
            List<Element> selectList = rootElement.selectNodes("//select");
            for (Element element : selectList) {
                String id = element.attributeValue("id");
                String paramterType = element.attributeValue("paramterType");
                String resultType = element.attributeValue("resultType");
                String sql = element.getTextTrim();
                MappedStatement mappedStatement = new MappedStatement();
                mappedStatement.setId(id);
                mappedStatement.setParamterType(paramterType);
                mappedStatement.setResultType(resultType);
                mappedStatement.setSql(sql);
                String statementId = namespace+"."+id;
                configuration.getMappedStatementMap().put(statementId,mappedStatement);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

}
